package top.tervest.easyshare.common.security.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import top.tervest.easyshare.common.util.AuthUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author ZhangNanNan
 * @create 2019-07-18 11:19
 */
@Component
public class AuthorizationTokenFilter extends OncePerRequestFilter {

    @Value("${security.token.name}")
    private String tokenName;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {

        String token = httpServletRequest.getHeader(tokenName) != null? httpServletRequest.getHeader(tokenName):"";
        Authentication authentication = null;
        if (!Objects.isNull(token)) {
            authentication = AuthUtil.getAuthentication(token);
        }
        if (Objects.isNull(authentication)) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }else {
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(httpServletRequest, httpServletResponse);
         }

    }
}
